<template>
  <div class="permissions-wrap">
    <el-row :gutter="10">
      <el-col :span="9" :xs="24">
        <el-card style="margin-bottom:20px;">
          <div slot="header" class="clearfix">
            <el-row style="display: flex; flex-direction: row; align-items: center">
              <el-col :span="6" :xs="24">
                <span>权限树</span>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-input-number
                  v-model="treeExpends"
                  size="mini"
                  :min="1"
                  :max="treeMaxLength"
                  label="展开层级"
                  @change="treeChangeExpends"
                />
              </el-col>
            </el-row>
          </div>
          <el-tree
            :data="dataTree"
            :props="defaultProps"
            node-key="id"
            highlight-current
            :default-expanded-keys="expandedIds"
            :expand-on-click-node="false"
            :render-content="renderContent"
          />
        </el-card>
      </el-col>
      <el-col :span="15" :xs="24">
        <el-card style="margin-bottom:20px;">
          <div slot="header" class="clearfix">
            <span>权限详情（ {{ cardStatus }} ）</span>
          </div>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item :label="form.id.label">
                  <el-input v-model="form.id.value" :disabled="true" :placeholder="form.id.placeholder" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="form.path.label" prop="path">
                  <el-input
                    v-model="form.path.value"
                    :disabled="form.path.disable"
                    :placeholder="form.path.placeholder"
                    @input="pathChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label="form.name.label" prop="name">
                  <el-input
                    v-model="form.name.value"
                    :disabled="form.name.disable"
                    :placeholder="form.name.placeholder"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="form.regular.label" prop="regular">
                  <el-input
                    v-model="form.regular.value"
                    :disabled="form.regular.disable"
                    :placeholder="form.regular.placeholder"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item :label="form.component.label" prop="component">
                  <el-input
                    v-model="form.component.value"
                    :disabled="form.component.disable"
                    :placeholder="form.component.placeholder"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="form.weight.label" prop="weight">
                  <el-input
                    v-model="form.weight.value"
                    :disabled="form.weight.disable"
                    :placeholder="form.weight.placeholder"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item :label="form.pid.label" prop="pid">
                  <el-input v-model="form.pid.value" :disabled="true" :placeholder="form.pid.placeholder" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="form.permission.label" prop="permission">
                  <el-input
                    v-model="form.permission.value"
                    :disabled="true"
                    :placeholder="form.permission.placeholder"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item :label="form.dataStatus.label" prop="dataStatus">
                  <el-switch v-model="form.dataStatus.value" :disabled="form.dataStatus.disable" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="form.createDate.label">
                  <el-input
                    v-model="form.createDate.value"
                    :disabled="true"
                    :placeholder="form.createDate.placeholder"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row style="margin-top: 30px;">
              <el-col :span="4" :offset="16">
                <el-button type="default" :disabled="nowFormStatus === 'default' ? true : false" @click="onCancel">
                  取消
                </el-button>
              </el-col>
              <el-col :span="4" :offset="0">
                <el-button
                  type="primary"
                  :disabled="nowFormStatus === 'default' ? true : false"
                  @click="onSubmit('form')"
                >提交
                </el-button>
              </el-col>
            </el-row>

          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { add, update, deleteFn } from '@/api/permission'
import { getPermissionTree } from './generateTree'
import { computedUrlPermissions, checkPermission } from '@/utils/CommonUtils'

const form = {
  id: {
    disable: true,
    value: '',
    placeholder: '数据库主键',
    require: false,
    senBack: true,
    label: 'ID'
  },
  path: {
    disable: true,
    value: '',
    placeholder: 'api路径',
    require: false,
    senBack: true,
    label: '权限路径'
  },
  name: {
    disable: true,
    value: '',
    placeholder: '显示标题',
    require: true,
    senBack: true,
    label: '菜单名称'
  },
  regular: {
    disable: true,
    value: '',
    placeholder: '不能随意添加',
    require: false,
    senBack: true,
    label: '图标路径'
  },
  component: {
    disable: true,
    value: '',
    placeholder: '前端组件名称',
    require: false,
    senBack: true,
    label: '页面组件'
  },

  permission: {
    disable: true,
    value: '',
    placeholder: '访问规则',
    require: false,
    senBack: true,
    label: '访问规则'
  },
  weight: {
    disable: true,
    value: '100',
    placeholder: '菜单排序，同级值越大越靠前',
    require: false,
    senBack: true,
    label: '菜单排序'
  },
  dataStatus: {
    disable: true,
    value: true,
    placeholder: '是否启用',
    require: false,
    senBack: true,
    label: '是否启用'
  },
  createDate: {
    disable: true,
    value: '',
    placeholder: '创建时间',
    require: false,
    senBack: false,
    label: '创建时间'
  },
  pid: {
    disable: false,
    value: '',
    placeholder: '父菜单ID',
    require: false,
    senBack: true,
    label: '父菜单ID'
  }
}
export default {
  data() {
    return {
      dataTree: [],
      form,
      cardStatus: '默认',
      absolutePath: '',
      iconsMap: [],
      selectIconVisible: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      nowFormStatus: 'default',
      rules: {},
      expandedIds: [],
      treeExpends: 2,
      treeMaxLength: 20
    }
  },
  created() {
    this.loadData()
  },

  mounted() {
    let str
    const rules = {}
    for (str in form) {
      if (form[str].require) {
        rules[str] = [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
    this.rules = rules
  },

  methods: {

    // 路径改变根据规则自动计算 路径
    pathChange(envet) {
      this.form.permission.value = computedUrlPermissions(this.form.path.value)
    },

    append(data) {
      const tempForm = JSON.parse(JSON.stringify(form))
      tempForm.pid.value = data.id
      let str
      for (str in tempForm) {
        tempForm[str].disable = false
      }
      this.form = tempForm
      this.cardStatus = '“' + data.name + ' ” 下添加菜单'
      this.nowFormStatus = 'add'
    },

    edit(data) {
      const tempForm = JSON.parse(JSON.stringify(form))
      let str
      for (str in tempForm) {
        tempForm[str].disable = false
        tempForm[str].value = data[str]
      }
      this.form = tempForm
      this.nowFormStatus = 'update'
      this.cardStatus = `编辑 “${data.name}”`
    },

    remove(node, data) {
      this.removeForm(data)
    },

    removeForm(data) {
      this.$bus.emit('conformDialog', { title: '提示', content: '此操作将永久删除该文件, 是否继续?', successFn: () => {
        deleteFn([data.id]).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.$store.dispatch('user/getUser')
          this.reset()
        })
      } })
    },

    onSubmit(formData) {
      const formParms = this.form
      const params = {}
      let str, item
      for (str in formParms) {
        item = formParms[str]
        if (item.senBack) {
          if (item.require && !item.value) {
            this.$message({
              type: 'warning',
              message: `请填写 ${item.label}`
            })
            return false
          }
          params[str] = item.value
        }
      }
      params.dataStatus = params.dataStatus ? 1 : 0
      params.weight = parseInt(params.weight)
      if (this.nowFormStatus === 'add') {
        delete params.id
        add(params).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功！'
          })
          this.reset()
          this.$store.dispatch('user/getUser')
        })
      } else {
        update(params).then(res => {
          this.$message({
            type: 'success',
            message: `更新成功!`
          })
          this.reset()
          this.$store.dispatch('user/getUser')
        })
      }
    },
    onCancel() {
      this.form = form
      this.nowFormStatus = 'default'
      this.cardStatus = '默认'
    },

    renderContent(h, { node, data, store }) {
      const addPermissions = !checkPermission('/resources/add')
      const editPermissions = !checkPermission('/resources/update')
      const deletPermissions = !checkPermission('/resources/deletes')
      // jsx react
      return (
        <div
          style='flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 12px; padding-right: 8px;'>
          <div class='overflowhidden' style='display: inline-block; max:120px;'>
            <span>{data.name}</span>
          </div>
          <span>
            <el-button style='font-size: 12px; color:#67C23A; margin-left:6px;' type='text'
              on-click={() => this.append(data)} disabled={addPermissions}> 新增</el-button>
            <el-button style='font-size: 12px;' type='text' disabled={editPermissions} on-click={() => this.edit(data)}> 编辑</el-button>
            <el-button style='font-size: 12px; color:#F56C6C;' type='text' disabled={deletPermissions}
              on-click={() => this.remove(node, data)}>删除</el-button>
          </span>
        </div>)
    },

    reset() {
      this.loadData(true)
      this.onCancel()
    },

    // 改变动态框
    treeChangeExpends(expends) {
      console.log(expends)
      this.loadData(false)
    },

    loadData(flush) {
      getPermissionTree(flush, this.treeExpends).then(res => {
        console.log(res)
        this.dataTree = res.trees
        this.expandedIds = res.expands
        this.treeMaxLength = res.maxLength
      })
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  $color-blue: #2196F3;
  $space-width: 18px;
  @import "~@/styles/variables.scss";

  .overflowhidden{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .permissions-wrap{
    padding:10px 0;
    overflow-x: hidden;
  }

  .tree-ctrl {
    cursor: pointer;
  }

  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: $space-width;
    height: 14px;
    &::before {
      content: ""
    }
  }

  .processContainer {
    width: 100%;
    height: 100%;
  }

  table td {
    line-height: 26px;
  }

  .tree-ctrl {
    position: relative;
    cursor: pointer;
    color: $color-blue;
    margin-left: -$space-width;
  }

</style>
